<?php

namespace app\admin\controller\livestreamer;

use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\Model;

/**
 * 主播账户表，将爬取到的主播账号全部记录在此表中，机器人在爬取新主播时，需先在此表中查询是否存在； 
表中记录了主播的状态信息。
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Livestreamer模型对象
     * @var \app\admin\model\Livestreamer
     */
    protected $noNeedLogin = ['checkuser'];
    protected $model = null;
    protected $admin = null;

    protected $searchFields = 'livestreamerUser';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Livestreamer;
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("contacttypeList", $this->model->getContacttypeList());
        $this->view->assign("signstatusList", $this->model->getSignstatusList());
        $this->view->assign("checkstatusList", $this->model->getCheckstatusList());
        $this->view->assign("gradeList", $this->model->getGradeList());

        $this->admin = new Admin();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['livestreamerUser','gender','age','faceLevel','fansNum','language','region','videoNum','spiderType','contactType','checkStatus','checkRemark','checkTime','grade','signature','spiderRobotUser']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $agentlist = $this->get_user_list();
        return $this->view->fetch('',['agentlist'=>$agentlist]);
    }
    public function checkrobot()
    {
        $params = $this->request->post();
        $list = Db::table('robotuser_list')->where(['agentID'=>$params['agent'],'robotType'=>1])->where('status',1)->select();
        $html ="<option value=''>全部</option>";
        foreach ($list as $vv) {
            $html.="<option value='".$vv['robotUser']."'>".$vv['robotUser']."</option>";
        }
        $this->success('','',['html'=>$html]);
    }
    public function artific()
    {
        if ($this->request->isAjax()) {
        
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            //$params = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                $param = "'" . $params['livestreamerUser'] . "'," . $params['grade'] . ",'" . $params['checkRemark'] . "',". $params['contractType'] . ",'".$params['contract']."',@_res";
                Db::query("call livestreamer_grade_log(".$param.")");
                $result = true;
                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }
        $jjr = $this->get_user_list();

//        $robotUser = db('robotuser_list')->where([
//            "robotType" => 1,
//            "agentID" => $this->auth->username
//        ])->select();

        $admin = $this->admin->where([
            'status' => 'normal'
        ])->select();

        $list = [];
        foreach ($admin as $item => $value) {
            $list[$value->username] = $value->username;
        }

//        $robotUserList = [];
//        foreach ($robotUser as $v) {
//            $robotUserList[$v['robotUser']] = $v['robotUser'];
//        }


        return $this->view->fetch('',['jjr'=>$jjr, 'adminList' => $list]);
    }

    public function manual()
    {
        if ($this->request->isAjax()) {
        
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $userlist = $params['userlist'];
            $params = $this->preExcludeFields($params);
            $result = false;
            $num = 0;
            Db::startTrans();
            try {
                foreach ($userlist as $vv) {
                    $user = Db::table('livestreamer_list')->where('livestreamerUser',$vv['unique_id'])->find();
                    if (!$user) { //查询数据中已有,没有则添加
                        $vv['gender'] = 0;
                        $vv['age'] = 0;
                        $vv['beauty'] = 0;
                        //百度ai人脸识别 线上环境测试
                        //$avatar = $vv['avatar_thumb']['url_list'][0];
                        //测试先用一张国内图片 //https://d-gonghui.bigchun.com/meinv1.jpg
                        $avatar = 'https://d-gonghui.bigchun.com/meinv1.jpg';
                        $baidur = $this->model->baiduimgrun($avatar);
                        $baidur = json_decode($baidur,true);
                        if (isset($baidur['error_code'])&&$baidur['error_code']==0) {
                            $vv['gender'] = $baidur['result']['face_list'][0]['gender']['type']=='female'?2:1;
                            $vv['age'] = $baidur['result']['face_list'][0]['age'];
                            $vv['beauty'] = $baidur['result']['face_list'][0]['beauty'];
                        }else{
                            $this->error($baidur['error_msg']);
                        }
                        //解析最新视频发布时间
                        $url = "https://tokapi-mobile-version.p.rapidapi.com/v1/post/user/".$vv['uid']."/posts";
                        $videos = json_decode($this->curl_get($url),true);
                        $newVideoTime = '0000-00-00 00:00:00';
                        $videolist = [];
                        if (isset($videos['aweme_list'])) {
                            $newVideoTime = date('Y-m-d H:i:s',$videos['aweme_list'][0]['create_time']);
                            $videolist = $videos['aweme_list'];
                        }
                        //解析个人签名联系方式
                        if(strpos($vv['signature'],'instagram')!==false){
                            $vv['contactType'] = 1;
                        }elseif(strpos($vv['signature'],'facebook')!==false){
                            $vv['contactType'] = 2;
                        }elseif(strpos($vv['signature'],'whatsapp')!==false){
                            $vv['contactType'] = 3;
                        }elseif(strpos($vv['signature'],'wechat')!==false){
                            $vv['contactType'] = 4;
                        }else{
                            $vv['contactType'] = 0;
                        }
                        $vv['contact'] = "";
                        $reg= "/15[0-9]\d{8}|17[0-9]\d{8}|14[0-9]\d{8}|13[0-9]\d{8}|18[0-9]\d{8}|19[0-9]\d{8}/";
                        preg_match_all($reg,$vv['signature'],$resd);
                        if (isset($resd[0][0])) {
                            $vv['contact'] = $resd[0][0];
                        }
                        $param = "'".$vv['unique_id']. "'," . $vv['uid'] . ",'" . $vv['nickname'] . "','" . $vv['avatar_thumb']['url_list'][0] . "',".$vv['gender'].",".$vv['age'].",".$vv['beauty'].",".$vv['language'].",".$vv['region'].",".$vv['following_count'].",".$vv['follower_count'].",".$vv['total_favorited'].",'".$vv['signature']."','".$newVideoTime."','adminrobot',2,'".$vv['twitter_id']."','".$vv['twitter_name']."','".$vv['youtube_channel_id']."','".$vv['youtube_channel_title']."',@_res";
                        Db::query('call livestreamer_add('.$param.')');
                        $index = 0;
                        foreach ($videolist as $va) {
                            $index++;
                            $videoindex = $index;
                            $videocoveraddr = $va['video']['cover']['url_list'][0];
                            $videoplayaddr = $va['video']['play_addr']['url_list'][0];
                            Db::query('call add_user_video_addr('.$vv['uid'].',"'.$vv['unique_id'].'",'.$videoindex.',"'.$videocoveraddr.'","'.$videoplayaddr.'",@_res)');
                        }
                        $num++;
                    }
                }
                
                $result = true;
                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success('添加成功'.$num.'条','',['num'=>$num]);
        }
        $jjr = $this->get_user_list();
        return $this->view->fetch('',['jjr'=>$jjr]);
    }

    public function checkuser()
    {
        $params = $this->request->post();
        //halt($params);
        $userlist = [];
        foreach ($params['zhuboarr'] as $value) {
            //halt($value);
            $url = "https://tokapi-mobile-version.p.rapidapi.com/v1/user/username/".$value;
            $userinfo = json_decode($this->curl_get($url),true);
            if (isset($userinfo['uid'])) {
                $url = "https://tokapi-mobile-version.p.rapidapi.com/v1/user/".$userinfo['uid'];
                $users = json_decode($this->curl_get($url),true);
                $userlist[] = $users['user'];
            }
        }
        $html = "";
        foreach ($userlist as $vv) {
            $html .= "<tr>";
            $html .= "<td>".$vv['uid']."</td>";
            $html .= "<td>".$vv['nickname']."</td>";
            $html .= "<td>".$vv['follower_count']."</td>";
            $html .= "<td>未知</td>";
        }
        if (!$html) {
            $this->error('查询不到主播信息');
        }
        $this->success('查询成功','',['html'=>$html,'arr'=>json_encode($userlist)]);
    }

    public function checkZhuboDetail()
    {
        $params = $this->request->post();
        // halt($params);
        $userinfo = [];
        $videolist = [];
        if ($params['uid']) {
            $userinfo = Db::table('livestreamer_list')->where('userid',$params['uid'])->find();
            $videolist = Db::table('user_video_addr')->where('userid',$params['uid'])->select();
            // $url = "https://tokapi-mobile-version.p.rapidapi.com/v1/post/user/".$params['uid']."/posts";
            // $postslist = json_decode($this->curl_get($url),true);
            // if (isset($postslist['aweme_list'])) {
            //     $videolist = $postslist['aweme_list'];
            // }
        }else{
            $this->error('无有效的uid');
        }
        $html = "";
        $inx = 0;
        foreach ($videolist as $vv) {
            // $inx++;
            // if ($inx<=4) {
            //     $html .= '<div class="col-xs-8 col-sm-3">';
            //     $html .= '<img class="img-responsive" data-vurl="'.$vv['video']['play_addr']['url_list'][0].'" src="'.$vv['video']['cover']['url_list'][0].'" alt="">';
            //     $html .= '</div>';
            // }
            $html .= '<div class="col-xs-8 col-sm-3">';
            $html .= '<img class="img-responsive" data-vurl="'.$vv['videoplayaddr'].'" src="'.$vv['videocoveraddr'].'" alt="">';
            $html .= '</div>';
            
        }
        // if (!$html) {
        //     $this->error('查询不到主播信息');
        // }
        $this->success('查询成功','',['html'=>$html,'userinfo'=>$userinfo]);
    }

    public function checkzhubo()
    {
        $params = $this->request->post();
        $where = [];
        $order = '';
        // if (isset($params['agent']) && $params['agent']) {
        //     $where['signAgentID'] = $params['agent'];
        // }
        if (isset($params['robot']) && $params['robot']) {
            $where['spiderRobotUser'] = $params['robot'];
        }
        if (isset($params['gender']) && $params['gender']) {
            $where['gender'] = $params['gender'];
        }
        // if (isset($params['channel']) && $params['channel']) {
        //     $where['channel'] = $params['channel'];
        // }
        if (isset($params['checkStatus']) && $params['checkStatus']) {
             $where['checkStatus'] = $params['checkStatus'];
        }
        if (isset($params['grade']) && $params['grade']) {
             $where['grade'] = $params['grade'];
        }
        if (isset($params['region']) && $params['region']) {
            $where['region'] = $params['region'];
       }
        // if (isset($params['fansNum']) && $params['fansNum']) {
        //     $where['fansNum'] = ['between',$params['fansNum']];
        // }
        // if (isset($params['videoNum']) && $params['videoNum']) {
        //     $where['videoNum'] = ['between',$params['videoNum']];
        // }
        if (isset($params['order']) && $params['order']) {
            $order = $params['order'].' desc';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize']) ? $params['pageSize'] : 10;
        $total = Db::table('livestreamer_list')->where($where)->count();
        $total_page = ceil($total/$pageSize);
        $zhubolist = Db::table('livestreamer_list')->where($where)->order($order)->limit(($page - 1)*$pageSize,$pageSize)->select();
        $html = '';
        $row = 10;
        foreach ($zhubolist as $vv) {
            if ($vv['gender']==0) {
                $vv['gender'] = '未知';
            }elseif($vv['gender']==1){
                $vv['gender'] = '男';
            }elseif($vv['gender']==2){
                $vv['gender'] = '女';
            }elseif($vv['gender']==3){
                $vv['gender'] = '中性';
            }
            if ($vv['contactType']==0) {
                $vv['contactType'] = '无';
            }elseif($vv['contactType']==1){
                $vv['contactType'] = 'instagram';
            }elseif($vv['contactType']==2){
                $vv['contactType'] = 'facebook';
            }elseif($vv['contactType']==3){
                $vv['contactType'] = 'whatsapp';
            }elseif($vv['contactType']==4){
                $vv['contactType'] = 'wechat';
            }
            // modify by zht
            if ($vv['grade']==-1) {
                $vv['grade'] = '未复检';
            }elseif($vv['grade']==0){
                $vv['grade'] = '放弃';
            }elseif($vv['grade']==1){
                $vv['grade'] = '合格';
            }elseif($vv['grade']==2){
                $vv['grade'] = '优质';
            }
            //{:__('Time of the latest work')}
            if ($vv['checkStatus']==-1) {
                $vv['checkStatus'] = '未检测';
            }elseif($vv['checkStatus']==0){
                $vv['checkStatus'] = '不可签';
            }elseif($vv['checkStatus']==1){
                $vv['checkStatus'] = '可签约';
            }
            
           $html.='<tr class="kts" data-id="'.$vv['userid'].'">';
           
           $html.='<td>'.$vv['livestreamerUser'].'</td>';
           $html.='<td>'.$vv['gender'].'</td>';
           $html.='<td>'.$vv['age'].'</td>';
           $html.='<td>'.$vv['faceLevel'].'</td>';
           $html.='<td>'.$vv['language'].'</td>';
           $html.='<td>'.$vv['region'].'</td>';
           $html.='<td>'.$vv['videoNum'].'</td>';
           $html.='<td>'.$vv['contactType'].'</td>';
           //$html.='<td>'.$vv['contact'].'</td>';
           $html.='<td>'.$vv['checkStatus'].'</td>';
           $html.='<td>'.$vv['checkRemark'].'</td>';
           $html.='<td>'.$vv['grade'].'</td>';
           //$html.='<td>'.$vv['signature'].'</td>';
           //$html.='<td>'.$vv['spiderRobotUser'].'</td>';
           $html.='</tr>'; 
           $row--;
        }
        if ($row>0) {
            for ($i=0; $i < $row; $i++) { 
                $html.='<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>'; 
            }
        }
        $this->success('查询成功','',['html'=>$html,'pages'=>$page,'totalpage'=>$total_page]);
    }

    public function curl_get($url)
    {
        $curl = curl_init();

        // 本地测试去除ssl验证 正式上线后去除
        // curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);//整证curl对等证书(一只要此废)
        // curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);//检查服务器SSL证书中是否存在一个公用名
        // curl_setopt($curl,CURLOPT_SSLVERSION,0);//传递一个包SSL版本的长参数。
        /*end*/

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => [
                "X-RapidAPI-Host: tokapi-mobile-version.p.rapidapi.com",
                "X-RapidAPI-Key: cac81e5590msh18226afbb3026eap1c0c45jsn607825d6c677"
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return "cURL Error #:" . $err;
        } else {
            $resarr = json_decode($response,true);
            if (isset($resarr['message'])) {
                $this->error($resarr['message']);
            }
            return $response;
        }
    }
    //获取爬虫负责人列表
    public function get_robot_list()
    {

       //$list = Db::table('spiderrobot_work_sum')->where('status',0)->field('robotUser')->select();
       $list = Db::table('spiderrobot_work_sum')->where('status',0)->field('robotUser')->select();
        return $list;
    }
    //获取经纪人列表
    public function get_user_list()
    {

       $list = Db::table('admin')->where('status','normal')->field('id,username,nickname')->select();
        return $list;
    }
}
